
package com.cmc.dao.hibernate;

import java.util.List;

import com.cmc.dao.hibernate.BaseDaoHibernate;
import com.cmc.model.Department;
import com.cmc.dao.DepartmentDao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class DepartmentDaoHibernate extends BaseDaoHibernate implements DepartmentDao {

    /**
     * @see com.cmc.dao.DepartmentDao#getDepartments(com.cmc.model.Department)
     */
    public List getDepartments(final Department department) {
        //return getHibernateTemplate().find("from Department");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.*/
        if (department == null) {
            return getHibernateTemplate().find("from Department");
        } else {
            // filter on properties set in the department
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(department).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Department.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.cmc.dao.DepartmentDao#getDepartment(Long id)
     */
    public Department getDepartment(final Long id) {
        Department department = (Department) getHibernateTemplate().get(Department.class, id);
        if (department == null) {
            log.warn("uh oh, department with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(Department.class, id);
        }

        return department;
    }

    /**
     * @see com.cmc.dao.DepartmentDao#saveDepartment(Department department)
     */    
    public void saveDepartment(final Department department) {
        getHibernateTemplate().saveOrUpdate(department);
    }

    /**
     * @see com.cmc.dao.DepartmentDao#removeDepartment(Long id)
     */
    public void removeDepartment(final Long id) {
        getHibernateTemplate().delete(getDepartment(id));
    }
}
